package cn.edu.ysu.zry.service;

import cn.edu.ysu.zry.config.ConfigZhongxin;
import cn.edu.ysu.zry.entity.ZhongJiedian;
import cn.edu.ysu.zry.network.MessagePack;
import cn.edu.ysu.zry.network.NetWorkThreadZhongxin;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

/**
 * @program: XieyiBlockChainOS
 * @description: 服务提供类 - 中心节点
 * @author: Ruiyuan Zhang
 * @create: 2020-04-20 22:10
 */
public class ServiceZhongxin {
    public static void getZhongList(Socket socket){
        try {
            // 1 获取输出流
            OutputStream outputStream = socket.getOutputStream();

            // 2 获取重节点列表，填充到message封装类中
            ArrayList<ZhongJiedian> zlist=ConfigZhongxin.zhongJiedianArrayList;
            ZhongJiedian currentZhongJiedian=ConfigZhongxin.currentZhongJiedian;
            JSONObject jsonObject=new JSONObject();
            jsonObject.append("zlist",zlist);
            jsonObject.append("currentZhongJiedian",currentZhongJiedian);
            MessagePack<JSONObject> msg = new MessagePack<>();
            msg.setMessage("success");

            // 3 将数据写回请求中
            outputStream.write(msg.getBytes());

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
    *@Description: 处理某个节点的接入请求
    *@Param: JSONObject jsonObject：请求时发送的请求对象
    *@return:
    *@Author: Ruiyuan Zhang
    *@date: 2020/4/21
    */
    public static void linkTo(JSONObject jsonObject) {
        /**
         * 理论上应该要求data为加密后的数据，我进而可以确认是本人的请求
         * 但是在这里我打算使用明文传输
         */
        ZhongJiedian zhongJiedian=JSONUtil.toBean(jsonObject.getJSONObject("data"),ZhongJiedian.class);
        /** 这里应该加上对于重节点列表的锁定，以防止重节点和主线程对于这一资源的访问冲突 **/
        ConfigZhongxin.applyZhongJiedianArrayList.add(zhongJiedian);
    }
}
